﻿using System.Collections;
using System.Collections.ObjectModel;
using KinonekoSoftware.Foundation.UI.ViewModels;
using KinonekoSoftware.Foundation.UI.Controls;

namespace KinonekoSoftware.Foundation.UI.ViewModels
{
    public abstract class SelectionDialog<T> :
        ObjectDialog<IList<T>>,
        IMultiplePurposeSelector,
        ISelectionDialog<T> where T : class
    {
        private object _selectedItem;
        private object _selectedItems;

        protected SelectionDialog()
        {
            Collection = new ObservableCollection<T>();
        }

        protected List<T> GetSelection()
        {

            if (IsMultipleSelection)
            {
                return (SelectedItems as IEnumerable)
                      .Cast<T>()
                      .ToList();
            }

            return new List<T>
            {
                SelectedItem as T,
            };
        }


        protected override IList<T> OnFinish(bool editing)
        {
            return GetSelection();
        }

        protected virtual void OnSelectionChanged(object oldValue, object newValue)
        {

        }

        protected override void CreateValidationRules(ICollection<DialogRule> rules)
        {
        }

        protected void SetSelectedItems(object newValue)
        {
            SetValue(ref _selectedItems, newValue, nameof(SelectedItems));
        }

        protected void SetSelectedItem(object newValue)
        {
            SetValue(ref _selectedItem, newValue, nameof(SelectedItem));
        }

        public object SelectedItems
        {
            get => _selectedItems;
            set
            {
                OnSelectionChanged(_selectedItems, value);
                TryFinishAndSetValue(ref _selectedItems, value);
            }
        }

        public object SelectedItem
        {
            get => _selectedItem;
            set
            {
                OnSelectionChanged(_selectedItem, value);
                TryFinishAndSetValue(ref _selectedItem, value);
            }
        }
        
        public ObservableCollection<T> Collection { get; }


        public bool IsMultipleSelection { get; protected set; }
    }
}